package com;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Transaction;

import struct.CommentInfo;
import struct.SellerInfo;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;

import database.Helper;
@SuppressWarnings("serial")
public class CommentServlet extends HttpServlet 
{//client-server style (get input from client, then redirect output)
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException 
	{
		String msg = "";
		String seller = req.getParameter("seller");
		String username = req.getParameter("username");
		String comment = req.getParameter("comment");
		
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		if(comment == ""){
			//empty
			msg = "Error. Please enter a comment.";
			req.setAttribute("msg", msg);

			
			System.out.println(msg);

			req.getRequestDispatcher("error.jsp").forward(req, resp);
		}else{
			String current = "";
			DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
			
			java.util.Date currentDate = new java.util.Date();	
			current = df.format(currentDate);
			
			for (int j = 0; j < 10; j++) {
				Transaction tx = ds.beginTransaction();
				try {
					Entity e = new Entity("Comment");
					e.setProperty("SELLER", seller);
					e.setProperty("COMMENTOR", username);
					e.setProperty("COMMENT",comment);
					e.setProperty("TIME",current);
					//Blackboard style
					ds.put(tx, e);
					tx.commit();
					break;
					
					
				} catch (ConcurrentModificationException ed) {
					// continue
				} finally {
					if (tx.isActive())
						tx.rollback();
				}
			}	
			req.setAttribute("username", username);
			req.setAttribute("sellerInfo", Helper.GetSellerInfo(seller));
			req.setAttribute("commentInfo", Helper.GetCommentInfo(seller));
			
			
			req.getRequestDispatcher("sellerInfo.jsp").forward(req, resp);
		}
	}
	
}